package com.cloud.clouduser.security.common.controller;

import com.alibaba.fastjson.JSON;
import com.cloud.cloudcommons.pojo.CommonResult;
import com.cloud.cloudcommons.pojo.XltcResult;
import com.cloud.clouduser.security.base.SecurityPorperties;
import com.cloud.clouduser.security.base.SecurityUser;
import com.cloud.clouduser.security.wareable.WareAbleUserDetailsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.discovery.converters.Auto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Aurher: QiaoHang
 * @Description:
 * @Data: 2019/9/23 9:30
 * @Modified By:
 */
//用于配置表单登录
@RestController
public class CommonAuthenticationController {

    @GetMapping("/getAuthentication")
    public XltcResult getAuthentication(@AuthenticationPrincipal SecurityUser o){
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return XltcResult.success(o);
    }

    Logger logger = LoggerFactory.getLogger(getClass());
    //创建请求缓存
    RequestCache requestCache = new HttpSessionRequestCache();
    //创建重定向策略
    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    //配置属性类
    @Autowired
    SecurityPorperties securityPorperties;
    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    WareAbleUserDetailsService userDetailsService;

    /**
     * 所有需要验证授权的请求都跳转到这里，在这里统一配置 授权路径
     * @return
     */
    @RequestMapping("/authentication/required")
    public XltcResult  required(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //判断请求来自于什么地方html / restFul
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        String requestRedirectUrl = savedRequest.getRedirectUrl();
        logger.info("当前请求url:"+requestRedirectUrl);
        //如果请求是以.html 结尾，重定向到对应路径
        if(StringUtils.endsWithIgnoreCase(requestRedirectUrl,".html")){
            redirectStrategy.sendRedirect(request,response,securityPorperties.getBrowser().getLoginPage());
        }else {
            //这里是restFul 请求，跳转restFul请求认证的url
            return XltcResult.error("restFul请求需要被授权，请引导用户到登录页面");
        }
        return null;
    }

    /**
     * 授权失败写入浏览器返回值(触发)
     * @return
     */
    @RequestMapping("/authentication/error")
    public void authenticationError(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(objectMapper.writeValueAsString(CommonResult.ERROR));
    }

}
